//95_2_62_1  产品 id, cid 活动类型  activityid 活动id    pro_ident 第几个
var cart = {};
//加载本地购买物数据

//#region   主要用出显示本地购物车的数量不用跟服务费进行交互
cart.loadcartlocal=function (clubid) {
  return new Promise((resolve) => {
    var app = getApp();

    if(  app.globalData.cart){

      resolve( cart.loadcartlocal_data(clubid)  ) 
    }
    else
    {

      wx.getStorage({
        key: 'cart',
        success: function (res) {
          // 将数据从缓存里读出
          try {
            app.globalData.cart = JSON.parse(res.data);
           
    
          }
          catch (ex) {
            app.globalData.cart = {};
          }  

          resolve( cart.loadcartlocal_data(clubid)  ) 
        },
        fail: function (e) {
          app.globalData.cart = {};   
          resolve( cart.loadcartlocal_data(clubid)  ) 
        },
        complete: function (d) {  
       
        }
      })
    }
  }) 
}

cart.loadcartlocal_data =function(clubid){
  var app =getApp();
  var cartdata= app.globalData.cart

  for(var i in cartdata){

    if(cartdata[i].protype==2 && clubid!=cartdata[i].clubid){
    
      delete cartdata[i]
    }
  }
 
  return {cart:cartdata,totalnuminfo:cart.totalnuminfo(cartdata),groupcarnum:cart.groupbyactype(cartdata)}    
} 

cart.groupbyactype=function(htcart){
  var groupht={pro:{},prolimit:{}}

  var temlimitpro=null;
  for(var a in htcart){
   var temattr=  a.split("_");
   switch(temattr[1]){
     case "0":{
       if(!groupht["pro"][temattr[0]]){
        groupht["pro"][temattr[0]]=htcart[a]["num"]
       }
       else
       {
        groupht["pro"][temattr[0]]+=htcart[a]["num"]
       }   
       break;   
     }
     case "1":{
      if(  !groupht["prolimit"][temattr[2]]){
         groupht["prolimit"][temattr[2]]={};
      }
      temlimitpro =groupht["prolimit"][temattr[2]];
      if(!temlimitpro[temattr[0]]){
        temlimitpro[temattr[0]]=htcart[a]["num"]
      }
      else
      {
        temlimitpro[temattr[0]]+=htcart[a]["num"]
      }
      break;   
     }   
   }  
  }


 



  return groupht;
  
},

cart.totalnuminfo=function (cart) {
  var totalnum=0
  var selectednum=0;   
  var sumprice=0
  if(cart)
   {
     for(var a in cart){
  
      totalnum+= parseInt(cart[a]["num"]) ;
      if(cart[a].ischecked)
      {

        
        selectednum+= parseInt(cart[a]["num"]) ;
     
        if(cart[a].cid){
          cart[a].cid = cart[a].cid + "";
        }else{
          cart[a].cid = "0";
        }
       
          switch (cart[a].cid) {
            case "0": {
              sumprice = sumprice + cart[a].realprice * cart[a].num;
              break;
            }
            case "1": {
              sumprice = sumprice + cart[a].activityprice * cart[a].num;
              break;
            }
          }
        // var key=
        // if(a.indexOf("_1_")>0 ){
        //   sumprice+=cart[a]["num"]*cart[a].activityprice
        //   console.log("sumprice1111111")

        //   console.log(sumprice)
        // }
        // else
        // {

        //   console.log("sumprice222")

        //   sumprice+=cart[a]["num"]*cart[a].realprice
        //   console.log(sumprice)

        // }
       
      }
     }
   }
  
   return {totalnum,selectednum,sumprice};  
}
//#endregion

cart.loadcart = function () {
  var app = getApp();

  wx.getStorage({
    key: 'cart',
    success: function (res) {
      // 将数据从缓存里读出
      try {
        app.globalData.cart = JSON.parse(res.data);
       

      }
      catch (ex) {
        app.globalData.cart = {};
      }

      // return cart.loadcartPromise();
    },
    fail: function (e) {
      app.globalData.cart = {};

    },
    complete: function (d) {
    }
  })

  
}
cart.loadcartPromise = function (clubid) {
  var app = getApp();
  if (app.globalData.cart) {
    return cart.loadservedata(clubid);
  }
  else {
    return new Promise(function (resolve, reject) {
      wx.getStorage({
        key: 'cart',
        success: function (res) {
          // 将数据从缓存里读出
          try {
            app.globalData.cart = JSON.parse(res.data);
            cart.loadservedata(clubid).then(function (eda) {
              resolve(eda);
            }, function (edb) {
              reject(edb)
            })
          }
          catch (ex) {
            reject({ code: "faill", message: ex });
            app.globalData.cart = {};
          }
        },
        fail: function (e) {
          // reject({ code: "faill", message: e });
          resolve({ code: "success", data: [] });
          app.globalData.cart = {};
        }
      })
    })
  }
}
//订单重复购买
cart.buyagain = function (orderinfo) {
  orderinfo.forEach(function (item) {
    cart.querycartadd(item.keyval, item.num)
  })
}

cart.cleardada=function(){
  var app = getApp()

  return new Promise(function (resolve) {
    if (app.globalData.cart) {

      app.globalData.cart={}
  
      wx.setStorage({
        key: "cart",
        data: JSON.stringify(app.globalData.cart),
        success: function (et) {
          resolve({status:1})
        }    

      })
  
    }

  })
 
},

cart.getnum=function(){

  return new Promise(function (resolve, reject) {
    wx.getStorage({
      key: 'cart',
      success: function (res) {

        if(res.data)
        {

        }
      }      
       
    })
  })
  var app = getApp();
  if(app.globalData.cart){
    
  }

}
cart.loadservedata = function (clubid) {
  return new Promise(function (resolve, reject) {
    var app = getApp();
    var postdata = {};
    var keyvalues = Object.keys(app.globalData.cart);

    if (keyvalues.length < 1) {
      resolve({ code: "success", data: [] })
    }
    postdata["op"] = "getcartinfo";
    postdata["keyvalues"] = keyvalues.join(",");
    if(clubid>0){
      postdata['clubid']=clubid
    }
    app.util.request({
      'url': 'entry/wxapp/pro_cart',
      showLoading: false,
      'data': postdata,
      success: function (res) {
        if (res.data.errno == 0 && res.data.data["status"] == 1) {
          var invalidkeys=res.data.data["invalidkeys"];
          if(invalidkeys){
            for(var i in invalidkeys){
              cart.setnum(invalidkeys[i], 0)
            }
          } 
          var data = res.data.data["obj"];
          if (data && data.length > 0) {
            for (var a in data) {
              data[a]["num"] = app.globalData.cart[data[a]["keyval"]]["num"];
              if (app.globalData.cart[data[a]["keyval"]]["ischecked"]) {
                data[a]["ischecked"] = true
              }
              else {
                data[a]["ischecked"] = false;
              }
            }
            resolve({ code: "success", exinfo:res.data.data["exinfo"],data: data, nowtime: res.data.data["nowtime"] })
          }
          else {
            resolve({ code: "warn", data: data, nowtime: res.data.data["nowtime"] })
          }
        }
        else {
          reject({ code: "fail" });
        }
      },
      fail: function (res) {
        reject(((res.data && res.data.message) ? res.data.message : res.errMsg));
      },

    })
  })
}
/**
 * 删除选中
 */
cart.removeselected = function () {
  var app = getApp()
  if (app.globalData.cart) {

    for (var a in app.globalData.cart) {
      if (app.globalData.cart[a].ischecked) {
        delete app.globalData.cart[a]
      }
    }

    wx.setStorage({
      key: "cart",
      data: JSON.stringify(app.globalData.cart),
      success: function (et) {
      }
    })

  }
}
/**
 * 设定选中状态
 * @param {*} keyval 
 * @param {*} chkval 
 */
cart.setchk = function (keyval, chkval) {
  var app = getApp();
  
  app.globalData.cart[keyval]["ischecked"] = chkval;
  wx.setStorage({
    key: "cart",
    data: JSON.stringify(app.globalData.cart),
    success: function (et) {
    }
  })
}
/**
 * 更新数量
 */
cart.setnum = function (keyval, num,ischecked) {
  var app = getApp();
  if (num >= 1 && app.globalData.cart[keyval]) {
    app.globalData.cart[keyval]["num"] = num;

    if(ischecked&& !  app.globalData.cart[keyval]["num"]["ischecked"])
    {
      app.globalData.cart[keyval]["ischecked"]=ischecked;
    }
    
  }
  else {
    delete app.globalData.cart[keyval];

  }
  wx.setStorage({
    key: "cart",
    data: JSON.stringify(app.globalData.cart),
    success: function (et) {
    }
  })

}
//根据keys 快递加入简化步骤，这个有问题暂时不能用
cart.querycartadd = function (keyval, num, ischecked, cid, activityid) {
  var app = getApp();
  if (app.globalData.cart == null) {
    app.globalData.cart = {};
  }
  var attrkeys = keyval.split("_");
  attrkeys[1] = 1
  attrkeys[2] = 0
  if (!cid) {
    cid = 0;
  }

  if (!activityid) {
    activityid = 0;
  }
  if (!ischecked) {
    ischecked = true;
  }
  keyval = attrkeys.join("_");
  if (app.globalData.cart[keyval]) {
    app.globalData.cart[keyval]["num"] = num;
  }
  else {
    app.globalData.cart[keyval] = { keyval, num, activityid, ischecked }
  };
  // cid=0普通订单
  // promodel["keyval"] // "id_cid_activityid_attrs.join"   
  wx.setStorage({
    key: "cart",
    data: JSON.stringify(app.globalData.cart),
    success: function (et) {
    }
  })
},
  /**
   * promodel 加入的产品
   * cid 0普通订单
   * activityid =活动id
   */
  cart.cartadd = function (promodel, cid, activityid) {


    if(!promodel.protype){
      promodel.protype=1
    }
    promodel["ischecked"]=true
    
    var app = getApp();
    if (app.globalData.cart == null) {
      app.globalData.cart = {};
    }
    if (!cid) {
      cid = 0;
    }
    if (!activityid) {
      activityid = 0;
    }
    var arrkeyvals = [];
    arrkeyvals.push(promodel.id);
    arrkeyvals.push(cid);
    arrkeyvals.push(activityid);

    //  //95_2_62_1  产品 id, cid 活动类型  activityid 活动id    pro_ident 第几个 protype产品类型1商城产品2团长产品
    if (promodel.attrs && promodel.attrs.length > 0) {
      var attrs = [];
      for (var a in promodel.attrs) {
        attrs.push(promodel.attrs[a].keyval);
      }
      arrkeyvals.push(attrs.join("x"));
    }
    else {

      arrkeyvals.push("-1");
    }
    arrkeyvals.push(promodel.protype);
    var keyval = arrkeyvals.join("_");

    if (app.globalData.cart[keyval]) {
      app.globalData.cart[keyval]["num"] += parseInt(promodel["num"]);
    }
    else {
      app.globalData.cart[keyval] = promodel;
    }

    if(! app.globalData.cart[keyval]["ischecked"]){
      app.globalData.cart[keyval]["ischecked"] =true
    }
   
    


    // cid=0 普通订单
    // promodel["keyval"] // "id_cid_activityid_attrs.join"   
    wx.setStorage({
      key: "cart",
      data: JSON.stringify(app.globalData.cart),
      success: function (et) {
      }
    })
  }
module.exports = cart